'use strict';

const Service = require('egg').Service;

class EthService extends Service {
  // 验证地址的合法性
  isAddress(address) {
    const { app } = this;
    return app.BSC.Web3.isAddress(address);
  }

  // 获取地址的以太坊余额
  async getEthBalance2(address) {
    const { app, ctx } = this;
    const res = await app.BSC.Web3.trx.getBalance(address);
    return ctx.helper.div(res, app.Init.zero6)
  }

  // 获取以太坊当前的区块
  async getBlockNumber2() {
    const { app } = this;
    const res = await app.BSC.Web3.trx.getCurrentBlock();
    return res.block_header.raw_data.number;
  }

  // 获取指定区块的详情信息
  async getBlockMsg(blockNumber) {
    const { app } = this;
    return await app.BSC.Web3.trx.getBlockByNumber(blockNumber);
  }

  // 查询交易事务的详情信息
  // hash成功就是成功, 失败就是失败, 不存在就会报错, 刚发送也没有状态;
  async getTransaction2(hash) {
    const { app } = this;
    const res = await app.BSC.Web3.trx.getTransaction(hash);
    // true成功, false=失败
    console.log(res);
    return res.ret[0].contractRet === 'SUCCESS';
  }

  // 循环获取hash的状态
  // 如果hash不存在会报错
  // hash打包中就没有状态
  // hash是成功的res.ret[0].contractRet === 'SUCCESS';
  // hash是失败的res.ret[0].contractRet === 'REVERT'
  async myGetTransaction2(hash) {
    const { app } = this;
    // 间隔时间, 次数
    let time = 1000, number = 20;
    // 返回一个可同步对象
    let timer;
    return new Promise((resolve, reject) => {
      timer = setInterval(async () => {
        let res;
        try {
          // res = await app.BSC.Web3.trx.getTransaction(hash);
          res = await app.BSC.Web3.trx.getTransaction(hash);
        } catch (e) {
          // 报错; 抛出错误;
          /*if (e !== "Transaction not found") {
            reject('hash不存在');
          }*/
          reject('hash不存在');
          clearInterval(timer);
          return;
        }
        // 如果超过了次数, 不能无限等待; 抛出错误;
        if(number <= 0) {
          reject('hash出现了异常, 可能不存在或其它原因');
          clearInterval(timer);
          return;
        }
        if(!res.ret) {
          // 如果没有状态, 说明在打包中, 继续循环
          number -= 1;
        }else if(res.ret[0].contractRet === 'SUCCESS') {
          // 成功
          resolve(true);
          clearInterval(timer);
          return;
        }else {
          // 失败
          reject('hash执行失败');
          clearInterval(timer);
          return;
        }
      }, time);
    });
  }


  // trx默认地址转换16进制
  async addressToHex(address) {
    const { app } = this;
    return await app.BSC.Web3.address.toHex(address);
  }

  // 16进制地址转换成trx默认地址
  async addressFromHex(address) {
    const { app } = this;
    return await app.BSC.Web3.address.fromHex(address);
  }

  // trx默认地址转换16进制, 并且0x开头
  async addressToHex2(address) {
    const { app } = this;
    if (address.indexOf('0x') === 0) {
      return address;
    }
    address = await app.BSC.Web3.address.toHex(address);
    return address.replace('41', '0x');
  }


}

module.exports = EthService;
